package ruifeng.zcj.happymahjony.activity.sub;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;

import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXImageObject;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;

import java.io.IOException;
import java.util.HashMap;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketConnectionHandler;
import de.tavendo.autobahn.WebSocketException;
import ruifeng.zcj.happymahjony.AbJsonUtil;
import ruifeng.zcj.happymahjony.FragmentArgs;
import ruifeng.zcj.happymahjony.R;
import ruifeng.zcj.happymahjony.Result;
import ruifeng.zcj.happymahjony.ToActivityUtil;
import ruifeng.zcj.happymahjony.Utils;
import ruifeng.zcj.happymahjony.activity.base.BaseCordovaActivity;
import ruifeng.zcj.happymahjony.application.App;
import ruifeng.zcj.happymahjony.bean.sendRecord;
import ruifeng.zcj.happymahjony.listener.IsOpenSound;
import ruifeng.zcj.happymahjony.listener.ScreenListener;
import ruifeng.zcj.happymahjony.manager.ActivityManager;
import ruifeng.zcj.happymahjony.other.JSInterface;
import ruifeng.zcj.happymahjony.recordview.AudioUtil;
import ruifeng.zcj.happymahjony.recordview.VolumnUtil;
import ruifeng.zcj.happymahjony.util.BackgroundMusicUtil;
import ruifeng.zcj.happymahjony.util.DesUtil;
import ruifeng.zcj.happymahjony.util.FileNameUtils;
import ruifeng.zcj.happymahjony.util.FileUtils;
import ruifeng.zcj.happymahjony.util.PlayUtils;
import ruifeng.zcj.happymahjony.util.SPUtils;
import ruifeng.zcj.happymahjony.util.Util;

import static ruifeng.zcj.happymahjony.Utils.buildTransaction;

/**
 * Cordova主页<br/>
 */
public class MainCordovaActivity extends BaseCordovaActivity implements JSInterface.JSListener, ScreenListener.ScreenStateListener {

    private final String serverIP = "139.224.68.110";

    private final String serverPort = "9502";

    private WebSocketConnection socket;

    private AudioUtil audioUtil;

    private VolumnUtil volumnUtil;

    private BackgroundMusicUtil bgUtil;

    private String url;

    private String json;

    private ScreenListener screenListener;

    public void onCreate(Bundle savedInstanceState) {
        setFullScreen();
        super.onCreate(savedInstanceState);
        ActivityManager.getInstance().popActivity();
        setSplashScreen(R.mipmap.loginback2);
        setUrlTimeout(15 * 1000);
        initData();
        initListener();
        // 锁屏监听
        screenListener = new ScreenListener(this);
        screenListener.begin(this);
    }


    protected void onResume() {
        super.onResume();
        bgUtil.resumeBackgroundMusic();
    }

    protected void onStop() {
        super.onStop();
        bgUtil.pauseBackgroundMusic();
    }

    private void initData() {
        showToast("读取中，请稍后...");
        App.getInstance().setLoginSuccess(true);
        Result result = (Result) ((FragmentArgs) getIntent().getExtras().getSerializable("key")).get("result");
        url = "file:///android_asset/www/index.html#/NewRoom?mid=" + result.getMid() + "&mid=" + result.getToken() + "";
        super.loadUrl(url, 2000);
        socket = new WebSocketConnection();
        audioUtil = new AudioUtil();
        volumnUtil = new VolumnUtil(this, audioUtil);
        bgUtil = new BackgroundMusicUtil(this);
        bgUtil.playBackgroundMusic("www/audio/bgm.m4a", true);
    }

    private void initListener() {
        addJavascriptInterface();
    }

    private void addJavascriptInterface() {
        JSInterface js = new JSInterface();
        js.setShareListener(this);
        appView.addJavascriptInterface(js, "android");
        appView.getSettings().setAppCacheEnabled(true);
        appView.getSettings().setSupportZoom(false);
        appView.getSettings().setUseWideViewPort(true);
        appView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        appView.getSettings().setDomStorageEnabled(true);
    }

    public void invite(String param, String room) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://mj.lcc.so";
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "欢乐卡卡:" + room;
        msg.description = "房号:" + room + "欢乐卡卡，经典模式！请进入房间时输入房号，赶紧加入哦！";
        Bitmap thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_58);
        msg.thumbData = Utils.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = SendMessageToWX.Req.WXSceneSession;
        App.getInstance().getWXAPI().sendReq(req);
    }

    public void share(String text, Bitmap bitmap) {
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = "http://mj.lcc.so";
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = "【欢乐卡卡】";
        msg.description = "快捷方便的手机麻将，简单好玩，随时随地地组局，赶紧试试吧！点击即可下载哦！";
        Bitmap thumb;
        if (bitmap != null) {
            thumb = bitmap;
        } else {
            thumb = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_58);
//            thumb = BitmapFactory.decodeResource
        }
        msg.thumbData = Utils.bmpToByteArray(thumb, true);

        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        if (!text.isEmpty() && text.equals("2")) {// 朋友圈
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
        } else {// 好友
            req.scene = SendMessageToWX.Req.WXSceneSession;
        }
        Log.e("zcj", "11111111111111");
        App.getInstance().getWXAPI().sendReq(req);
    }

    /**
     * 分享朋友圈
     */
    public void shareCircle(String text) {
        share("2", null);
    }

    public void startRecord() {
        bgUtil.pauseBackgroundMusic();
        showToast("请开始说话");
        try {
            String path = FileNameUtils.getAudioFilePath(this, "hlkk", "audio");
            audioUtil.setAudioPath(path);
            audioUtil.recordAudio();
            runOnUiThread(new Runnable() {
                public void run() {
                    volumnUtil.showVolumnDialog();
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void finishRecord(String arg) {
        showToast("录音成功");
        bgUtil.resumeBackgroundMusic();
        audioUtil.stopRecord();
        volumnUtil.hideVolumnDialog();
        if (!socket.isConnected()) {
            json = arg;
            connect();
        } else {
            sendRecordFile(arg);
        }
    }

    public void cancelRecord() {
        showToast("取消录音");
        bgUtil.resumeBackgroundMusic();
        audioUtil.stopRecord();
        volumnUtil.hideVolumnDialog();
    }

    public void playCard(String name) {
        BackgroundMusicUtil sound = new BackgroundMusicUtil(this);
        sound.playBackgroundMusic("www/audio/" + name + ".m4a", false);
    }

    /**
     * 语音播放
     **/
    public void playRecord(String payload) {
        bgUtil.pauseResumeBackgroundMusic(5000);
        try {
            //         byte[] data = Base64.decode(payload, BIND_ABOVE_CLIENT);
//          PlayUtils.play(MainCordovaActivity.this, data);
            byte[] data = DesUtil.convertHexString(payload);
            PlayUtils.play(MainCordovaActivity.this, data);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 退出登录
     */
    public void exitLogin() {
        showToast("退出登录");
        SPUtils.put(this, SPUtils.USER_INFO, "");
        Intent intent = new Intent(this, MainActivity.class);
        startActivity(intent);
        finish();
    }

    // 打开/关闭背景音乐
    @Override
    public void controlBgm(String arg) {// 1 关闭   2  打开
        if (arg.equals("1")) {
            bgUtil.pauseBackgroundMusic();
        } else if (arg.equals("2")) {
            bgUtil.resumeBackgroundMusic();
        }
    }

    // 打开/关闭打牌音效
    @Override
    public void controlSound(String arg) {// 1 关闭    2 打开
        if (arg.equals("1")) {
            IsOpenSound.isSound = false;
        } else if (arg.equals("2")) {
            IsOpenSound.isSound = true;
        }
    }

    /**
     * 截屏幕
     */
    @Override
    public void shareAchievement() {
        shareTu(FileUtils.screenshot(this));
    }

    private static final int THUMB_SIZE = 150;

    public void shareTu(Bitmap bitmap) {
        if (bitmap != null) {
            Bitmap bmp = bitmap;
            WXImageObject imgObj = new WXImageObject(bmp);

            WXMediaMessage msg = new WXMediaMessage();
            msg.mediaObject = imgObj;

            Bitmap thumbBmp = Bitmap.createScaledBitmap(bmp, THUMB_SIZE, THUMB_SIZE, true);
//            bmp.recycle(); ：清空了这个堆内存
            msg.thumbData = Util.bmpToByteArray(thumbBmp, true);

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("img");
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            App.getInstance().getWXAPI().sendReq(req);
        }
    }

    private void connect() {
        showToast("正在连接");
        new Thread(new Runnable() {

            public void run() {
                final String wsuri = "ws://" + serverIP + ":" + serverPort;
                try {
                    socket.connect(wsuri, socketHandler);
                } catch (WebSocketException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void sendRecordFile(String arg) {
        sendRecord sendRecord = (ruifeng.zcj.happymahjony.bean.sendRecord) AbJsonUtil.fromJson(arg, sendRecord.class);
        showToast("正在发送");
        byte[] data = FileUtils.getBytes(audioUtil.getAudioPath());
        String text = null;
        try {
//          text = Base64.encodeToString(data, BIND_ABOVE_CLIENT);
            text = DesUtil.byte2HexString(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("type", "12");
        map.put("video", text);
        map.put("mid", "" + sendRecord.getMid());
        map.put("rid", "" + sendRecord.getRid());
        map.put("role", "" + sendRecord.getRole());
        map.put("token", "" + sendRecord.getToken());
        String json = AbJsonUtil.toJson(map);
        socket.sendTextMessage(json);
    }

    private WebSocketConnectionHandler socketHandler = new WebSocketConnectionHandler() {

        public void onOpen() {
            showToast("连接成功");
            if (json != null) {
                sendRecordFile(json);
                json = null;
            }
        }

        public void onTextMessage(String payload) {

        }

        public void onClose(int code, String reason) {
            if (code != 1) {
                showToast("服务器异常，请稍后再试");
            }
        }

    };

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && appView.canGoBack()) {
            appView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void onDestroy() {
        super.onDestroy();
        bgUtil.stopBackgroundMusic();
        if (socket != null && socket.isConnected()) {
            showToast("正在关闭");
            socket.disconnect();
        }
    }


    @Override
    public void onScreenOn() {

        ruifeng.zcj.happymahjony.util.Log.d("zcj", "onScreenOn开屏");

    }

    @Override
    public void onScreenOff() {
        ruifeng.zcj.happymahjony.util.Log.d("zcj", "onScreenOff锁屏了");

//        appView.loadUrl(url);

//        startActivity(Log);


    }

    @Override
    public void onUserPresent() {
        ruifeng.zcj.happymahjony.util.Log.d("zcj", "onScreenOn 解锁");

        ToActivityUtil.toNextActivityAndFinish(this, MainActivity.class);

    }

}
